package com.tony.thread;

import java.util.concurrent.*;

public class CyclicBarrierTest {
    static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 4, 60,
            TimeUnit.SECONDS,new LinkedBlockingDeque<>());
    static CyclicBarrier cb = new CyclicBarrier(3, new Runnable() {
        @Override
        public void run() {
            System.out.println("一起去打球！");
        }
    });
    static class GoThread extends Thread{
        final String name;
        public GoThread(String name){
            this.name = name;
        }
        @Override
        public void run() {
            System.out.println(name+"出发了");
            try {
                Thread.sleep(2000);
                //cb.await();
                cb.await(10,TimeUnit.SECONDS);
                System.out.println(name+"从楼下出发");
                //Thread.sleep(1000);
                System.out.println(name+"到达操场");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        String[] str= {"李明","王强","刘凯","赵杰"};
        String[] str1= {"王二","洪光","雷兵","赵三"};
        for(int i=0;i<str.length;i++){
            threadPoolExecutor.execute(new GoThread(str[i]));
        }
        try {
            Thread.sleep(4000);
            System.out.println("四个人一起到达球场，现在开始打球");
//            System.out.println("现在对CyclicBarrier进行复用.....");
//            System.out.println("又来了一拨人，看看愿不愿意一起打：");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        cb.reset();
//        for(int i=0;i<str.length;i++){
//            threadPoolExecutor.execute(new GoThread(str1[i]));
//        }
//        try {
//            Thread.sleep(4000);
//            System.out.println("4vs4");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

    }
}
